<?php
declare(strict_types=1);

namespace Service\GoodsService;

use Service\BaseService;
use App\Model\BbcModel\MnStoreGoods;
use Service\Code\Normal;
use Hyperf\DbConnection\Db;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsBatch;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\Goodsbrand;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\GoodsTags;
use Service\GoodsBrandService\BrandService;
use Service\HelperService\Common;
use Service\MemberService\VipService;
use Service\ActivityService\ActivityStoreService;
use Service\ConfigureService\ChannelConfigService;
use Service\ActivityService\CouponStoreService;

/**
 * 店铺商品服务中心
 * @author chenshubo
 */
class MnGoodsService extends BaseService {

    //店铺价格类型
    const TYPE_QQC_PROFIT_PRICE = 0;
    const TYPE_QQC_PROFIT_RATE = 1;
    const TYPE_QQC_COMMENT_PRICE = 2;
    const TYPE_QQC_DIY_PRICE = 3;

    /**
     * 批量获取利润额 零售价和会员价
     * @param int $mn_sid
     * @param array $goodsIds
     * @param int $baseSpec
     * @param int $level
     * @param int $spec_num
     * @return array
     */
    public function getGoodsAllProfit(int $mn_sid, array $goodsIds, int $baseSpec = 1, int $level = 0, int $spec_num = 0) {
        //获取店铺商品
        $mnStoreGoodsList = $this->queryMnGoodsList($mn_sid, $goodsIds);
        if (empty($mnStoreGoodsList)) {
            return Normal::returnCode(Normal::FAIL, "获取店铺商品明细失败");
        }

        //获取渠道商品
        $channelGoodsList    = ChannelGoodsService::instance()->queryGoodsList($goodsIds);
        $channelGoodsListMap = array_column($channelGoodsList, null, 'id');

        //获取商品规格价格
        $goodsSpecPriceList    = GoodsSpecPriceService::instance()->getGoodsSpecPriceList($goodsIds);
        $goodsSpecPriceMapList = GoodsSpecPriceService::instance()->getMapList($goodsSpecPriceList);

        //获取分销商等级价格数据
        $goodsDistributorList    = DistributorSpecPriceService::instance()->getGoodsDistributorPriceList($goodsIds);
        $goodsDistributorMapList = DistributorSpecPriceService::instance()->getMapList($goodsDistributorList);


        //获取店铺自定义价格
        $goodsMnSpecPriceList    = MnSpecGoodsService::instance()->getMnSpecPriceList($mn_sid, $goodsIds);
        $goodsMnSpecPriceMapList = MnSpecGoodsService::instance()->getMapList($goodsMnSpecPriceList);
        $_mn_profit_list         = [];
        foreach ($mnStoreGoodsList as $mnStoreGoods) {
            $goods_id = $mnStoreGoods['goods_id'];
            if (!isset($channelGoodsListMap[$goods_id])) {
                $mnStoreGoods['profit']     = 0;
                $mnStoreGoods['profit_vip'] = 0;
                $mnStoreGoods['status']     = 0;
                array_push($_mn_profit_list, $mnStoreGoods);
                continue;
            }


            $spec_num = $spec_num == 0 ? $baseSpec : $spec_num;
            $spec     = isset($goodsSpecPriceMapList[$goods_id][$spec_num]) ? $goodsSpecPriceMapList[$goods_id][$spec_num] : [];
            $goods    = $channelGoodsListMap[$goods_id];            
            if (!empty($spec)) {
                $goods['price_cost']          = $spec['price_cost'];
                $goods['price_store']         = $spec['price_store'];
                $goods['price_recommend']     = $spec['price_recommend'];
                $goods['price_recommend_vip'] = $spec['price_recommend_vip'];
                $goods['price_market']        = $spec['price_market'];
            }

            //如果是存在等级的情况下,需要得到分销商等级商品价格
            if ($level > 0) {
                if (isset($goodsDistributorMapList[$goods_id]) &&
                    isset($goodsDistributorMapList[$goods_id][$level]) &&
                    isset($goodsDistributorMapList[$goods_id][$level][$spec_num])) {
                    $levelPrice           = $goodsDistributorMapList[$goods_id][$level][$spec_num];
                    $goods['price_store'] = $levelPrice['price'];
                }
            }


            if (empty($mnStoreGoods) || $mnStoreGoods['type'] == self::TYPE_QQC_COMMENT_PRICE) {//推荐零售价
                $mnStoreGoods['profit']     = bcsub((string)$goods['price_recommend'], (string)$goods['price_store'], 2);
                $mnStoreGoods['profit_vip'] = bcsub((string)$goods['price_recommend_vip'],(string) $goods['price_store'], 2);
            } elseif ($mnStoreGoods['type'] == self::TYPE_QQC_PROFIT_RATE) {//全球仓店铺利润率
                $mnStoreGoods['profit']     = bcdiv(bcmul( (string)$goods['price_store'],(string)$mnStoreGoods['profit'], 3), '100', 3);
                $mnStoreGoods['profit_vip'] = bcdiv(bcmul( (string)$goods['price_store'],(string) $mnStoreGoods['profit_vip'],3), '100', 3);
            } elseif ($mnStoreGoods['type'] == self::TYPE_QQC_DIY_PRICE) {//自定义价格

                if (isset($goodsMnSpecPriceMapList[$goods_id]) && isset($goodsMnSpecPriceMapList[$goods_id][$spec_num])) {
                    $hasSpec                   = $goodsMnSpecPriceMapList[$goods_id][$spec_num];
                    $mnStoreGoods['price']     = $hasSpec['price'];
                    $mnStoreGoods['price_vip'] = $hasSpec['price_vip'];
                } else {
                    if ($goods['is_trade'] == 0)//代发
                    {
                        $mnStoreGoods['price']     = $goods['price_recommend'];
                        $mnStoreGoods['price_vip'] = $goods['price_recommend_vip'];
                    }
                }

                $mnStoreGoods['profit']     = bcsub($mnStoreGoods['price'], $goods['price_store'], 2);
                $mnStoreGoods['profit_vip'] = bcsub($mnStoreGoods['price_vip'], $goods['price_store'], 2);
            }


            if ($mnStoreGoods['profit'] <= 0) {
                $mnStoreGoods['profit'] = 0;
            }
            if ($mnStoreGoods['profit_vip'] <= 0) {
                $mnStoreGoods['profit_vip'] = $mnStoreGoods['profit'];
            }

            $mnStoreGoods['profit']              = round($mnStoreGoods['profit'], 2);
            $mnStoreGoods['profit_vip']          = round($mnStoreGoods['profit_vip'], 2);
            $mnStoreGoods['price_store']         = $goods['price_store'];
            $mnStoreGoods['tax_rate']            = $goods['tax_rate'];
            $mnStoreGoods['tax_free']            = $goods['tax_free'];
            $mnStoreGoods['price_market']        = $goods['price_market'];
            $mnStoreGoods['price_recommend']     = $goods['price_recommend'];
            $mnStoreGoods['price_recommend_vip'] = $goods['price_recommend_vip'];
            $mnStoreGoods['price_cost']          = $goods['price_cost'];
            array_push($_mn_profit_list, $mnStoreGoods);
        }

        return $_mn_profit_list;
    }

    /**
     * 批量获取店铺商品清单
     * @param int $mn_sid
     * @param array $goodsIds
     */
    public function queryMnGoodsList(int $mn_sid, array $goodsIds) {
        return MnStoreGoods::instance()
            ->where('mn_sid', $mn_sid)
            ->whereIn('goods_id', $goodsIds)
          //  ->where('df', '0')
            ->get()
            ->toArray();
    }

    /**
     * 批量获取店铺商品清单
     * @param int $mn_sid
     * @param array $goodsIds
     */
    public function queryMnGoodsListByGoodsIds(array $goodsIds) {
        return MnStoreGoods::instance()
            ->select([
                         'id',
                         'mn_sid',
                         'status',
                         'goods_id'
                     ])
            ->whereIn('goods_id', $goodsIds)
            ->get()
            ->toArray();
    }

    /**
     * 获取店铺商品列表数据
     * @param int $mn_sid
     * @param array $goodsIds
     */
    public function queryMnGoodsPageList(int $mn_sid) {
        return MnStoreGoods::instance()
            ->select([
                         Db::raw('lmsg.id as StoreGoodsID'),
                         Db::raw('lg.name as GoodsName'),
                         Db::raw('lg.id as GoodsID'),
                         Db::raw('lg.class_id as ClassID'),
                         Db::raw('lgb.name as BrandName'),
                     ])
            ->from('ly_mn_store_goods as lmsg')
            ->join('ly_goods as lg', 'lg.id', '=', 'lmsg.goods_id')
            ->join('ly_goods_brand as lgb', 'lgb.id', '=', 'lg.brand_id')
            ->join('ly_goods_class as lgc', 'lgc.id', '=', 'lg.class_id')
            ->where('lmsg.mn_sid', $mn_sid)
            ->where('lmsg.df', '0')
            ->limit(200)
            ->get()
            ->toArray();
    }

    /**
     * 获取商品列表数据
     * @param array $goods_ids
     * @param int $cid
     * @param int $mn_sid
     * @param array $ohter
     * @author: hj
     */
    public static function getGoodsListByGoodsIds(array $goods_ids, int $cid, int $mn_sid, $ohter = []) {
        if (empty($goods_ids) || empty($cid) || empty($mn_sid)) {
            return [];
        }
        $fields   = [
            'id', 'name', 'img', 'class_id', 'brand_id', 'skucode', 'is_trade', 'barcode', 'tax_rate', 'tax_free', 'status', 'is_bonded', 'is_sync',
            'price_store', 'cid', 'price_recommend', 'price_recommend_vip', 'body', 'price_cost', 'num_storage', 'price_market', 'fictitious_sale',
            'num_sale', 'df', 'medicinal', 'tag', 'supply_tag', 'pic_auth'
        ];
        $goodsAll = Goods::whereIn('id', $goods_ids)->where('cid', $cid)->select($fields)->get()->toArray();
        if ($goodsAll) {
            $goodsAll = array_column($goodsAll, null, 'id');
        }
        $mnStoreGoodsAll1 = MnStoreGoods::where('df', 0)->whereIn('goods_id', $goods_ids)->select(['goods_id', 'id'])->get()->toArray();
        $mnStoreGoodsAlls = [];
        if ($mnStoreGoodsAll1) {
            foreach ($mnStoreGoodsAll1 as $v) {
                $mnStoreGoodsAlls[$v['goods_id']][] = $v;
            }
        }
        $mnStoreGoodsAll = MnStoreGoods::where('mn_sid', (int)$mn_sid)->whereIn('goods_id', $goods_ids)->get()->toArray();
        if ($mnStoreGoodsAll) {
            $mnStoreGoodsAll = array_column($mnStoreGoodsAll, null, 'goods_id');
        }
        $goodsBatchAll = GoodsBatch::whereIn('goods_id', $goods_ids)->where('df', 0)->get();

        $level     = Mnuser::where('id', (int)$mn_sid)->value('level');
        $brand_ids = $goodsAll ? array_column($goodsAll, 'brand_id') : [];
        $brandAll  = BrandService::getBrand($brand_ids);

        $class_ids = $goodsAll ? array_column($goodsAll, 'class_id') : [];
        $classAll  = GoodsClass::whereIn('id', $class_ids)->pluck('name', 'id')->toArray();
        $showTag   = GoodsTags::where('cid', $cid)->where('show', 1)->select(['id', 'show_name', 'img', 'position'])->get()->toArray();

        $mnStoreGoodsUpdate1 = [];
        $mnStoreGoodsUpdate2 = [];
        $goodsUpdate         = [];
        $resultData          = [];
        foreach ($goods_ids as $goods_id) {
            $goods                = $goodsAll[$goods_id] ?? [];
            $mnStoreGoodsAllsByid = $mnStoreGoodsAlls[$goods_id] ?? [];
            if (empty($goods) || ($goods['is_trade'] == 0 && ($goods['df'] == 1 || $goods['status'] == 0))) {
                if (!empty($mnStoreGoodsAllsByid)) {
                    $delIds = array_column($mnStoreGoodsAllsByid, 'id');
                    // Rbq::instance()->pushNew($delList, 'store', 'delete');//后面再写
                }
                array_push($mnStoreGoodsUpdate1, $goods_id);
                // MnStoreGoods::instance()->edit(['df' => 0, 'goods_id' => $param['id']], ['df' => 1,'md'=>time()]);
                continue;
            }
            $mnGoods = $mnStoreGoodsAll[$goods_id] ?? [];
            if (!empty($mnGoods) && $mnGoods['pre_sell'] == 1 && $mnGoods['num'] == 0 && $goods['df'] == 1) {
                if (!empty($mnStoreGoodsAllsByid)) {
                    $delIds = array_column($mnStoreGoodsAllsByid, 'id');
                    // Rbq::instance()->pushNew($delList, 'store', 'delete');//后面再写
                }
                array_push($mnStoreGoodsUpdate2, $goods_id);
                // MnStoreGoods::instance()->edit(['df' => 0, 'goods_id' => $param['id']], ['df' => 1,'pre_sell '=>0,'md'=>time()]);
                continue;
            }
            if (!empty($mnGoods) && $mnGoods['num'] == 0 && $mnGoods['df'] == 1 && $mnGoods['pre_sell'] == 0 and $goods['is_trade'] == 1) {
                continue;
            }
            if (isset($ohter['status']) && $ohter['status'] == 1) {
                if (empty($mnGoods) || $mnGoods['status'] == 0) {
                    continue;
                }
            }
            $goods['status']   = $mnGoods['status'] ?? 0;
            $goods['up']       = $mnGoods['up'] ?? 0;
            $goods['pre_sell'] = $mnGoods['pre_sell'] ?? 0;
            if ($goods['price_store'] == 0) {
                $goods['price_store'] = $goods['price_cost'];
                array_push($goodsUpdate, $goods_id);
                Goods::where('id', $goods_id)->update(['price_store' => $goods['price_cost']]);
            }
            //由S2B同步的商品需要获取批次号和仓库列表
            if ($goods['is_trade'] == 1) {
                $has_batch = $goodsBatchAll->where('mn_sid', $mn_sid)->where('type', 1)->where('goods_id', $goods_id)->toArray();
            } else {
                $has_batch = $goodsBatchAll->where('goods_id', $goods_id)->where('type', 0)->toArray();
            }
            $spec_list = isset($has_batch['spec_list']) && !empty($has_batch['spec_list']) ? json_decode($has_batch['spec_list'], true) : [];
            $baseSpec  = 1;
            if (!empty($spec_list)) {
                $baseSpec = $spec_list[0]['spec_num'] ?? 1;
            }
            $goods['num_storage'] = $has_batch['num'] ?? 0;
            $goods['stoid']       = $has_batch['storage_id'] ?? 0;
            if ($goods['is_trade'] == 1) {
                $goods['num_storage'] = $mnGoods['num'] ?? 0;
            }
            //预售库存
            if ($goods['pre_sell'] == 1) {
                $goods['num_storage'] = !empty($mnGoods) ? $mnGoods['pre_storage'] : 0;
            }
            //C端价格
            $profitAll = MnStoreGoods::getGoodsAllProfit($mn_sid, [$goods_id], 1, $level);
            $profit    = $profitAll[$goods_id] ?? [];

            $goods['price_market']        = $profit['price_market'] ?? $goods['price_market'];
            $goods['price_store']         = $profit['price_store'];
            $goods['price_cost']          = sprintf("%.2f", round($goods['price_store'], 2));
            $goods['price_recommend']     = sprintf("%.2f", round($goods['price_recommend'], 2));
            $goods['price_recommend_vip'] = sprintf("%.2f", round($goods['price_recommend_vip'], 2));
            $goods['price']               = sprintf("%.2f", round($profit['profit'] + $goods['price_store'], 2));
            $goods['profit']              = sprintf("%.2f", round($profit['profit'], 2));
            $goods['price_vip']           = sprintf("%.2f", round($profit['profit_vip'] + $goods['price_store'], 2));
            $goods['profit_vip']          = sprintf("%.2f", round($profit['profit_vip'], 2));
            //品牌
            $brand      = $brandAll[$goods['brand_id']] ?? [];
            $class_name = $classAll[$goods['class_id']] ?? '';
            if (!empty($goods['img']) && strpos($goods['img'], 'http') === false) {
                $goods['img'] = Common::$pre_image_url . $goods['img'] . Common::$pic_level['small_resize'];
            }
            //商品标签
            $label = [];
            if (!empty($showTag)) {
                $tags = [];
                if (!empty($goods['tag'])) {
                    $tags = explode(',', $goods['tag']);
                }
                if (!empty($goods['supply_tag'])) {
                    $tags = array_merge($tags, explode(',', $goods['supply_tag']));
                }
                if (!empty($tags)) {
                    foreach ($showTag as $v) {
                        if (in_array($v['id'], $tags)) {
                            $label[] = $v;
                        }
                    }
                }
            }
            $data = [
                'id'                  => $goods['id'],
                'name'                => $goods['name'],
                'img'                 => $goods['img'],
                'body'                => $goods['body'],
                'barcode'             => $goods['barcode'],
                'skucode'             => $goods['skucode'],
                'is_trade'            => $goods['is_trade'],
                'is_bonded'           => $goods['is_bonded'],
                'num_sale'            => $goods['fictitious_sale'],
                'num_storage'         => $goods['num_storage'],
                'class_name'          => $class_name,
                'brand_name'          => !empty($brand['name']) ? $brand['name'] : '',
                'brand_country_name'  => !empty($brand['country_name']) ? $brand['country_name'] : '',
                'brand_country_icon'  => !empty($brand['country_icon']) ? $brand['country_icon'] : '',
                'is_sync'             => $goods['is_sync'],
                'stoid'               => $goods['stoid'],
                'baseSpec'            => $baseSpec,
                'price'               => $goods['price'],
                'price_vip'           => $goods['price_vip'],
                'price_store'         => $goods['price_store'],
                'price_cost'          => $goods['price_cost'],
                'price_recommend'     => $goods['price_recommend'],
                'price_recommend_vip' => $goods['price_recommend_vip'],
                'price_market'        => $goods['price_market'],
                'profit'              => $goods['profit'],
                'profit_vip'          => $goods['profit_vip'],
                'has_batch'           => $has_batch,
                'status'              => $goods['status'],
                'df'                  => $goods['df'],
                'is_medicinal'        => $goods['pic_auth'],
                'medicinal'           => $goods['medicinal'],
                'up'                  => $goods['up'],
                'pre_sell'            => $goods['pre_sell'],
                'tax_free'            => $goods['tax_free'],
                'tax_rate'            => $goods['tax_rate'],
                'label'               => $label,
            ];

            if (!empty($data['brand_country_icon']) && strpos($data['brand_country_icon'], 'http') === false) {
                $data['brand_country_icon'] = Common::$pre_image_url . $data['brand_country_icon'];
            }
            $resultData[$goods_id] = $data;
        }
        if ($mnStoreGoodsUpdate1) {
            MnStoreGoods::whereIn('goods_id', $mnStoreGoodsUpdate1)->where('df', 0)->update(['df' => 1, 'md' => time()]);
        }
        if ($mnStoreGoodsUpdate2) {
            MnStoreGoods::whereIn('goods_id', $mnStoreGoodsUpdate1)->where('df', 0)->update(['df' => 1, 'pre_sell ' => 0, 'md' => time()]);
        }
        return $resultData;
    }

     /**
     * 判断商品是否在店铺内，如果不在则上架，如果下架则上架，主要用于店铺模板设置
     * @param $mn_sid //店铺ID
     * @param $mid
     * @param array $goods_ids
     * @return bool
     */
    public function checkGoods($mn_sid,$mid,array $goods_ids = []){
        if(count($goods_ids) <= 0){
            return true;
        }
        $s = [];
        $mn_user = Mnuser::instance()->info(['id'=>$mn_sid]);
        //符合店铺的商品
        $mn_goods_list = Goods::instance()
            ->where('id','in',$goods_ids)
            ->where(['df'=>0,'status'=>1])
            ->where(function ($query) use ($mn_user){
                if($mn_user['type'] != 2){
                    $query->where(Db::raw("is_trade=0"));
                }
            })
            ->where(function ($query) use ($mn_user){
                if($mn_user['type']==3){
                    switch ($mn_user['goods_source']){
                        case 1://只卖普通仓
                            $query->where(Db::raw("(is_fast_delivery=0)"));
                            break;
                        case 2://只卖前置仓
                            $query->where(Db::raw("(supplier_id=$mn_user[supplier_id])"));
                            break;
                        case 3://前置仓+普通仓
                            $query->where(Db::raw("((supplier_id=$mn_user[supplier_id]) or (is_fast_delivery=0))"));
                            break;
                        case 4://只卖中心仓
                            $query->where(Db::raw("(is_fast_delivery=2)"));
                            break;
                        case 5://中心仓+普通仓
                            $query->where(Db::raw("(is_fast_delivery<>1)"));
                            break;
                        case 6://中心仓+前置仓
                            $query->where(Db::raw("((supplier_id=$mn_user[supplier_id]) or (is_fast_delivery=2))"));
                            break;
                        case 7://所有仓
                            $query->where(Db::raw("((supplier_id=$mn_user[supplier_id]) or (is_fast_delivery in (0,2)))"));
                            break;
                    }
                }else{
                    $query->where(Db::raw("(is_fast_delivery <> 1)"));
                }
            })
            ->field('id,name,class_id,brand_id')
            ->select()->toArray();
        if(!$mn_goods_list){
            return true;
        }
        $mn_goods_ids = array_column($mn_goods_list,'id');
        $mn_goods_map = array_column($mn_goods_list,null,'id');

        //已写入店铺商品表的商品
        $store_goods_list = MnStoreGoods::instance()
            ->where('goods_id','in',$mn_goods_ids)
            ->where(['mn_sid'=>$mn_sid])
            ->field('id,goods_id,df,status')
            ->select()->toArray();
        $store_goods_ids = array_column($store_goods_list,'goods_id');

        $diff_array = array_diff($mn_goods_ids,$store_goods_ids);//未写入店铺商品表的商品

        $store_goods_map = array_column($store_goods_list,null,'goods_id');

        Db::startTrans();
        try{
            $mnGoodsId = [];
            if($diff_array){ //未写入店铺商品的商品
                foreach ($diff_array as $v){
                    $insertData[] = [
                        'mn_sid'   => $mn_sid,
                        'goods_id' => $v,
                        'status'   => 1,
                        'cd'       => time(),
                        'type'     => 2,
                        'mnid'     => 2,
                        'mid'      => $mid,
                        'md'       => time(),
                    ];
                    $mnGoodsId[] = $v;
                }

                Db::table('ly_mn_store_goods')
                    ->insertAll($insertData);
            }
            $updateData = [];
            foreach ($mn_goods_ids as $v){
                if( isset($store_goods_list[$v]) && $store_goods_list[$v]['status'] == 0){ //下架的商品
                    $updateData[] = [
                        'id' => $store_goods_list[$v]['id'],
                        'status'   => 1,
                        'df'       => 0,
                        'md'       => time(),
                    ];
                    $mnGoodsId[] = $v;
                }
            }
            if(count($updateData) > 0 ){
                MnStoreGoods::instance()->saveAll($updateData);
            }

            //更新ES索引
            if(count($mnGoodsId) > 0){
                $goods_brand_ids = array_column($mn_goods_list,'brand_id');
                $brand_list = Goodsbrand::instance()
                    ->where('id','in',$goods_brand_ids)
                    ->field('id,name')
                    ->select()->toArray();
                $brand_list_map = array_column($brand_list,null,'id');
                $insertData = [];
                foreach ($mnGoodsId as $g){
                    $insertItem['id']         = $g;
                    $insertItem['goodsId']    = $g;
                    $insertItem['name']       = $mn_goods_map[$g]['name'];
                    $insertItem['classifyID'] = $mn_goods_map[$g]['class_id'];
                    $insertItem['storeID']    = $mn_sid;
                    $insertItem['brandName']  = $brand_list_map[$mn_goods_map[$g]['brand_id']]['name'] ?? '';
                    $insertItem['isActive']   = true;

                    $insertData[] = $insertItem;
                }
                Rbq::instance()->pushNew($insertData,'store','insert');
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
        return true;
    }

    /**
     * 获取小C端商品的列表详情
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     * @param array $goods_ids
     * @param int $status
     * @param array $mn_user
     * @param array $mn_user_activity_goods //特价活动
     * @return mixed
     */
    public function goodsListFormat(int $cid,int $mn_sid,int $mid,array $goods_ids,int $status = 1,array $mn_user,array $mn_user_activity_goods = [])
    {
        if( empty($goods_ids) ) {
            return [];
        }

        $goodsList = $this->formatGoods($cid,$mn_sid,$status,$goods_ids,$mn_user);

        $mn_user_activity_goods_map = array_column($mn_user_activity_goods,null,'goods_id');


        //处理黑卡问题
        $checkUserIsBlackVipCards       = VipService::instance()->checkUserIsBlackVipCard($mn_user,[$mid]);
        $checkUserIsBlackVipCardsMap    = array_column($checkUserIsBlackVipCards,null,'mid');

        //vip数据
        $is_vip = $checkUserIsBlackVipCardsMap[$mid];

        //获取店铺商品促销
        $activityList       = ActivityStoreService::instance()->getStoreActivity($cid, $mn_sid, $mid, $mn_user,$goods_ids, $is_vip);
        $activityListMap    = array_column($activityList,null,'goods_id');
        //优惠券
        $couponMap       = CouponStoreService::instance()->getStoreCoupon($cid,$mn_sid,$goods_ids,$mn_user,$mid,$activityListMap);
//        $couponMap    = array_column($coupon,null,'goods_id');
        foreach ($goodsList as & $item)
        {
            $goods_id           = $item['id'];
            $item['activity']   = $mn_user_activity_goods_map[$goods_id] ?? null;
            $item['is_special'] = 0;

            //商品促销
            $activity = $activityListMap[$goods_id] ?? [
                'fullActivity'      => null,
                'fullActivityInfo'  => null,
                'goodsActivity'     => null,
                'bookActivity'      => null,
                'seckillActivity'   => null,
                'detailTag'         => null,
                'listTag'           => null,
                'fullTag'           => '',
                'sendActivity'      => 0,
            ];
            if (!empty($item['activity']))
            {
                $info = $item['activity'];
                if ( $info['type'] == 2 ) {
                    //特价活动
                    $item['price_store']    = $item['price'];
                    $item['price']          = $info['price'];
                    $item['is_special']     = 1;
                }
            }
            else
            {
                if( $activity['fullActivity'] || $activity['goodsActivity']) { //有整单促销或满减促销没有特价，使用推荐零售价
                    $item['price'] = $item['price_recommend'];
                    $item['price_vip'] =  $item['price_recommend_vip'];
                }
            }

            $item['tag'] = $activity['listTag'];

            //优惠券
            if(empty($info) && !empty($couponMap[$goods_id]) )
            {
                $coupon = $couponMap[$goods_id];
                if(!empty($coupon['listTag'])){
                    if(empty($item['tag'])){
                        $item['tag'] = $coupon['listTag'];
                    }else{
                        $item['tag'] = array_merge($item['tag'],$coupon['listTag']);
                    }
                }
            }
            if(is_array($item['tag'])){
                $item['tag'] = array_values(array_filter($item['tag']));
            }
            if(empty($item['tag'])){
                $item['tag'] = null;
            }
            $item['price_left'] = round($item['price']-$item['price_vip'],1);
//            unset( $item['price_recommend']);
//            unset( $item['price_recommend_vip']);
        }
        return $goodsList;
    }

    /**
     * C端接口使用
     * @param int $cid
     * @param int $status
     * @param int $mn_sid
     * @param array $goods_ids
     * @param array $mn_user
     * @return mixed
     */
    public function formatGoods(int $cid, int $mn_sid, int $status, array $goods_ids, array $mn_user)
    {

        $goodsList = ChannelGoodsService::instance()->queryBaseGoodsList($cid,$mn_sid,$status,$goods_ids,$mn_user);
        //价格小数设置
        $settingConfig = ChannelConfigService::instance()->getChannelConfig('price_decimal', $cid);
        $settingPrice  = $settingConfig['price'] ?? 0;
        //循环处理价格
        $getGoodsList = [];
        foreach ($goodsList as & $goods)
        {
            $item = [];
            $item['id']                 = $goods['id'];
            $item['name']               = $goods['name'];
            $item['img']                = $goods['img'];
            $item['num_sale']           = $goods['num_sale'];
            $item['is_bonded']          = $goods['is_bonded'];
            $item['num_storage']        = $goods['num_storage'];
            $item['brand_name']         = $goods['brand_name'];
            $item['brand_country_name'] = $goods['brand_country_name'];
            $item['brand_country_icon'] = $goods['brand_country_icon'];
            $item['brand_pic']          = $goods['brand_country_icon'];
            $item['pre_sell']           = $goods['pre_sell'];
            $item['medicinal']          = $goods['is_medicinal'];
            $item['price_type']         = $goods['medicinal'];
            $item['baseSpec']           = $goods['baseSpec'];
            $item['class_id']           = $goods['class_id'];
            $item['brand_id']           = $goods['brand_id'];
            $item['class_name']         = $goods['class_name'];
            $item['price_market']       = $goods['price_market'];//市场价
            /*$item['price_recommend']    = $goods['price_recommend'];
            $item['price_recommend_vip']= $goods['price_recommend_vip'];*/
            /*$item['price']              = $goods['price'];
            $item['price_vip']          = $goods['price_vip'];*/
            $item['base_spec']          = $goods['base_spec'];

            if($goods['base_spec'] != 1){ //不是单规格商品
                $goods['price']     = round($goods['price'] / $goods['base_spec'], 2);
                $goods['price_vip'] = round($goods['price_vip'] / $goods['base_spec'], 2);
                $goods['price_cost']         = round($goods['price_cost'] / $goods['base_spec'], 2);
                $goods['price_recommend']     = round($goods['price_recommend'] / $goods['base_spec'], 2);
                $goods['price_recommend_vip'] = round($goods['price_recommend_vip'] / $goods['base_spec'], 2);
//                $goods['profit']         = round($goods['profit'] / $goods['base_spec'], 2);
            }
            if( $settingPrice == 0 ) {
                if($goods['is_bonded']==1 && $goods['tax_free']==0){
                    $item['price'] = upDecimal($goods['price'] + $goods['price'] * $goods['tax_rate'], 1);

                    $item['price_vip']           = upDecimal($goods['price_vip'] + $goods['price_vip'] * $goods['tax_rate'], 1);
                    $item['price_recommend']     = upDecimal($goods['price_recommend'] + $goods['price_recommend'] * $goods['tax_rate'], 1);
                    $item['price_recommend_vip'] = upDecimal($goods['price_recommend_vip'] + $goods['price_recommend_vip'] * $goods['tax_rate'], 1);
                }else{
                    $item['price']               = upDecimal($goods['price'], 1);
                    $item['price_vip']           = upDecimal($goods['price_vip'], 1);
                    $item['price_recommend']     = upDecimal($goods['price_recommend'], 1);
                    $item['price_recommend_vip'] = upDecimal($goods['price_recommend_vip'], 1);
                }
            }else{
                if($goods['is_bonded']==1 && $goods['tax_free']==0){//计算税费
                    $item['price']               = ceil($goods['price'] + $goods['price'] * $goods['tax_rate']);
                    $item['price_vip']           = ceil($goods['price_vip'] + $goods['price_vip'] * $goods['tax_rate']);
                    $item['price_recommend']     = ceil($goods['price_recommend'] + $goods['price_recommend'] * $goods['tax_rate']);
                    $item['price_recommend_vip'] = ceil($goods['price_recommend_vip'] + $goods['price_recommend_vip'] * $goods['tax_rate']);
                }else{
                    $item['price']               = ceil($goods['price']);
                    $item['price_vip']           = ceil($goods['price_vip']);
                    $item['price_recommend']     = ceil($goods['price_recommend']);
                    $item['price_recommend_vip'] = ceil($goods['price_recommend_vip']);
                }
            }

            $item['price_cost'] = $goods['price_store'];//成本价
            $item['label'] = $goods['label'];
            array_push($getGoodsList, $item);
        }
        return $getGoodsList;
    }
}
